package comm.suger.web.utils;

import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName: TimerUtils
 * @Description: Timer工具类
 * @author Lanxiaowei
 * @date 2014-2-23 下午8:28:36
 */
public class TimerUtils {
	private Timer timer;
	protected Hashtable<Object, TimerTask> ht = null;

	public TimerUtils() {
		timer = new Timer();
		ht = new Hashtable<Object, TimerTask>();
	}

	/**
	 * 按周期执行
	 * 
	 * @param it
	 * @param firstTime
	 * @param period
	 * @param taskIDKey
	 */
	public void schedule(TimerTask it, Date firstTime, long period, Object taskIDKey) {
		if (it != null) {
			timer.schedule(it, firstTime, period);
			ht.put(taskIDKey, it);
		}
	}

	/**
	 * 定时执行
	 * 
	 * @param it
	 * @param firstTime
	 * @param taskIDKey
	 */
	public void schedule(TimerTask it, Date firstTime, Object taskIDKey) {
		if (it != null) {
			timer.schedule(it, firstTime);
			ht.put(taskIDKey, it);
		}
	}

	/**
	 * 取消所有任务计划
	 */
	public void cancelAll() {
		Enumeration<TimerTask> e = ht.elements();
		while (e.hasMoreElements()) {
			((TimerTask) e.nextElement()).cancel();
		}
	}

	/**
	 * 取消任务计划
	 * 
	 * @param id
	 */
	public void cancel(Object id) {
		if (ht.containsKey(id) && ht.containsValue(ht.get(id)))
			((TimerTask) ht.get(id)).cancel();
	}

	public void remove(Object id) {
		cancel(id);
		ht.remove(id);
	}

	public void stopSchedule() {
		timer.cancel();
	}
}
